package com.shanzmoo.merchant.server.api.manager.member;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shanzmoo.base.bean.PageRespBase;
import com.shanzmoo.base.bean.SHttpResponse;
import com.shanzmoo.base.util.CollectionUtil;
import com.shanzmoo.db.module.member.domain.query.CMemberCardBillQuery;
import com.shanzmoo.db.module.member.domain.query.CMemberCouponQuery;
import com.shanzmoo.db.module.member.domain.query.MemberAccountPageQuery;
import com.shanzmoo.db.module.member.domain.query.MemberMerchantIdPageQuery;
import com.shanzmoo.db.module.member.domain.vo.*;
import com.shanzmoo.db.module.member.entity.*;
import com.shanzmoo.db.module.member.service.*;
import com.shanzmoo.db.module.merchant.entity.MerchantInfoEntity;
import com.shanzmoo.db.module.merchant.service.IMerchantInfoService;
import com.shanzmoo.db.util.TimeUtils;
import com.shanzmoo.merchant.server.api.util.SecurityUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class MemberManager {

    @Autowired
    private IMemberMerchantService memberMerchantService;
    @Autowired
    private IMemberInfoService memberInfoService;
    @Autowired
    private IMemberCardConfigService memberCardConfigService;
    @Autowired
    private IMemberCardConfigDetailService memberCardConfigDetailService;
    @Autowired
    private IMemberCouponService memberCouponService;
    @Autowired
    private IMemberAccountRecordService memberAccountRecordService;
    @Autowired
    private IMemberAccountScoreRecordService accountScoreRecordService;
    @Autowired
    private IMemberCouponConfigService memberCouponConfigService;
    @Autowired
    private IMemberActivityConfigService memberActivityConfigService;
    @Autowired
    private IMemberActivityConfigDetailService memberActivityConfigDetailService;
    @Autowired
    private IMerchantInfoService merchantInfoService;
    @Autowired
    private IMemberMerchantTmpService memberMerchantTmpService;
    /**
     * 会员详情
     * @return
     */
    public SHttpResponse<CMemberDetailVO> detail() {
        CMemberDetailVO response = new CMemberDetailVO();
        Integer currentUserId = SecurityUtil.getCurrentUserId();
        MemberMerchantEntity currentMember = memberMerchantService.getById(currentUserId);
        if (currentMember == null){
            return SHttpResponse.fail(50001,"商户会员不存在");
        }
        MerchantInfoEntity merchantInfoEntity = merchantInfoService.getByMerchantCode(currentMember.getMerchantCode());
        if (merchantInfoEntity!=null){
            response.setMerchantName(merchantInfoEntity.getName());
        }
        response.setBalance(currentMember.getBalance());
        response.setCardNo(currentMember.getCardNo());
        response.setNickName(currentMember.getNickname());
        MemberInfoEntity memberInfoEntity = memberInfoService.getById(currentMember.getMemberInfoId());
        if (memberInfoEntity!=null){
            response.setScore(memberInfoEntity.getScore());
        }
        return SHttpResponse.ok(response);
    }

    /**
     * 充值活动列表
     * @return
     */
    public SHttpResponse<List<CMemberRechargeActivityVO>> rechargeActivityList() {
        Integer currentUserId = SecurityUtil.getCurrentUserId();
        MemberMerchantEntity currentMember2 = memberMerchantService.getById(currentUserId);
        MemberMerchantTmpEntity curretMemberTmp = memberMerchantTmpService.getById(currentUserId);
        String merchantCode = "";
        if (currentMember2 == null && curretMemberTmp == null){
            return SHttpResponse.fail(50001,"商户会员不存在");
        }
        if (curretMemberTmp!=null){
            merchantCode = curretMemberTmp.getMerchantCode();
        }
        if (currentMember2 !=null){
            merchantCode = currentMember2.getMerchantCode();
        }
        MemberCardConfigEntity memberCardConfigEntity = memberCardConfigService.getbyMerchantCode(merchantCode);
        if (memberCardConfigEntity == null){
            return SHttpResponse.fail(50002,"商户会员卡配置为空");
        }
        List<MemberCardConfigDetailEntity> memberCardConfigDetailEntities = memberCardConfigDetailService.getbyConfigId(memberCardConfigEntity.getId());
        if (memberCardConfigDetailEntities.size()<3){
            return SHttpResponse.ok();
        }
        List<CMemberRechargeActivityVO> collect = memberCardConfigDetailEntities.stream().map(a -> {
            CMemberRechargeActivityVO re = new CMemberRechargeActivityVO();
            re.setCardConfigDetailId(a.getCardConfigId());
            re.setGiveAmt(a.getGiveAmt());
            re.setRechargeAmt(a.getDefaultAmt());
            re.setRecommend(false);
            return re;
        }).collect(Collectors.toList());

        return SHttpResponse.ok(collect);
    }

    /**
     * 会员优惠券列表
     * @param query
     * @return
     */
    public SHttpResponse<PageRespBase<CMemberCouponVO>> couponList(CMemberCouponQuery query) {
        Integer currentUserId = SecurityUtil.getCurrentUserId();
        if (currentUserId==null){
            return SHttpResponse.fail(50001,"商户会员不存在");
        }
        query.setCurrentUserId(currentUserId);
        IPage<CMemberCouponVO> page = memberCouponService.queryCByRequest(query);
        PageRespBase pageRespBase = PageRespBase.create(page);

        return SHttpResponse.ok(pageRespBase);
    }

    public SHttpResponse<PageRespBase<CMemberAccountRecordVO>> cardBillList(CMemberCardBillQuery query) {
        Integer currentUserId = SecurityUtil.getCurrentUserId();
        if (currentUserId==null){
            return SHttpResponse.fail(50001,"商户会员不存在");
        }
        MemberMerchantEntity currentUser = memberMerchantService.getById(currentUserId);
        if (currentUser==null){
            return SHttpResponse.fail(50001,"商户会员不存在");
        }
        MemberAccountPageQuery query2= new MemberAccountPageQuery();
        query2.setPageNum(query.getPageNum());
        query2.setPageSize(query.getPageSize());
        query2.setMemberMerchantId(currentUserId);
        IPage<MemberAccountRecordVO> memberAccountRecordVOIPage = memberAccountRecordService.queryByRequest(query2);
        List<CMemberAccountRecordVO> convert = CollectionUtil.convert(memberAccountRecordVOIPage.getRecords(), CMemberAccountRecordVO.class);
        PageRespBase pageRespBase = PageRespBase.create(memberAccountRecordVOIPage, convert);
        return SHttpResponse.ok(pageRespBase);
    }

    public SHttpResponse<CMemberScorePageVO<CMemberScoreRecordVO>> scoreList(CMemberCardBillQuery query) {
        Integer currentUserId = SecurityUtil.getCurrentUserId();
        if (currentUserId==null){
            return SHttpResponse.fail(50001,"商户会员不存在");
        }
        MemberMerchantEntity byId = memberMerchantService.getById(currentUserId);
        MemberInfoEntity memberInfoEntity = memberInfoService.getById(byId.getMemberInfoId());
        MemberMerchantIdPageQuery request = new MemberMerchantIdPageQuery();
        request.setPageNum(query.getPageNum());
        request.setPageSize(query.getPageSize());
        request.setId(currentUserId);
        Page<MemberAccountScoreRecordEntity> memberAccountScoreRecordEntityPage = accountScoreRecordService.getbyMemberIdPage(request);
        List<CMemberScoreRecordVO> convert = CollectionUtil.convert(memberAccountScoreRecordEntityPage.getRecords(), CMemberScoreRecordVO.class);
        PageRespBase pageRespBase = CMemberScorePageVO.create(memberAccountScoreRecordEntityPage, convert);
        CMemberScorePageVO cMemberScorePageVO = new CMemberScorePageVO();
        cMemberScorePageVO.setCurrentScore((long)memberInfoEntity.getScore());
        List<MemberAccountScoreRecordEntity> memberAccountScoreRecordEntities = accountScoreRecordService.getbyMemberId(memberInfoEntity.getId());
        if (CollectionUtil.isNotEmpty(memberAccountScoreRecordEntities)){

            //支出总积分
            long expense = memberAccountScoreRecordEntities.stream().filter(a -> a.getScore() < 0).mapToLong(MemberAccountScoreRecordEntity::getScore).sum();
            cMemberScorePageVO.setExpenseTotalScore(expense);
            //获得总积分
            long getTotal = memberAccountScoreRecordEntities.stream().filter(a -> a.getScore() > 0).mapToLong(MemberAccountScoreRecordEntity::getScore).sum();
            cMemberScorePageVO.setGetTotalScore(getTotal);
            //当前积分
            BeanUtils.copyProperties(pageRespBase,cMemberScorePageVO);
        }
        return SHttpResponse.ok(cMemberScorePageVO);
    }

    public SHttpResponse<CMemberActivityByAmtVO> getActivity(Long orderAmt) {
        Integer currentUserId = SecurityUtil.getCurrentUserId();
        if (currentUserId==null){
            return SHttpResponse.fail(50001,"商户会员不存在");
        }
        MemberMerchantEntity currentUser = memberMerchantService.getById(currentUserId);
        if (currentUser==null){
            return SHttpResponse.fail(50001,"商户会员不存在");
        }
        CMemberActivityByAmtVO cMemberActivityByAmtVO = new CMemberActivityByAmtVO();
        List<CMemberCanUseActivityListVO> activityList = getCanUseActivity(orderAmt,currentUser);
        //可使用的活动
        cMemberActivityByAmtVO.setActivityList(activityList);


        //可使用的优惠券
        List<CMemberCanUseCouponListVO> couponList = getCanUserCouponList(orderAmt,currentUser);
        cMemberActivityByAmtVO.setCouponList(couponList);
        return SHttpResponse.ok(cMemberActivityByAmtVO);
    }

    /**
     * 获取用户可参加的活动
     * @param orderAmt
     * @param currentUser
     * @return
     */
    private List<CMemberCanUseActivityListVO> getCanUseActivity(Long orderAmt, MemberMerchantEntity currentUser) {
        String merchantCode = currentUser.getMerchantCode();
        List<MemberActivityConfigEntity> memberActivityConfigEntities = memberActivityConfigService.getbyMerchantCode(merchantCode);
        for (MemberActivityConfigEntity activityConfigEntity: memberActivityConfigEntities){
            LocalDateTime startTime = activityConfigEntity.getStartTime();
            LocalDateTime endTime = activityConfigEntity.getEndTime();
            if (activityConfigEntity.getStatus()!=1 || !TimeUtils.between(startTime,endTime,LocalDateTime.now())){
                continue;
            }
        }

        return null;
    }

    /**
     * 可使用的优惠券
     * @param orderAmt
     * @return
     */
    private List<CMemberCanUseCouponListVO> getCanUserCouponList(Long orderAmt, MemberMerchantEntity currentUser) {
        //用户所有未使用的优惠券
        List<MemberCouponEntity> memberCouponEntities =  memberCouponService.listByMemberMerchantId(currentUser.getId());
        //查询优惠券配置表，查询有效的券

        if (CollectionUtil.isEmpty(memberCouponEntities)){
            return null;
        }
        List<MemberCouponConfigEntity> memberCouponConfigEntities = memberCouponConfigService.listByIds(memberCouponEntities.stream().map(MemberCouponEntity::getCouponConfigId).collect(Collectors.toList()));
        if (CollectionUtil.isEmpty(memberCouponConfigEntities)){
            return null;
        }
        List<Integer> activityCouponConfigIds = new ArrayList<>();
        for (MemberCouponConfigEntity me:memberCouponConfigEntities){
            //查询有效的优惠券
            LocalDateTime startTime = me.getStartTime();
            LocalDateTime endTime = me.getEndTime();
            Integer type = me.getType();
            Long ruleFull = me.getRuleFull();
            if (TimeUtils.between(startTime,endTime,LocalDateTime.now()) && orderAmt>=ruleFull){
                activityCouponConfigIds.add(me.getId());
            }
        }
        if (CollectionUtil.isEmpty(activityCouponConfigIds)){
            return null;
        }
        List<MemberCouponEntity> collect = memberCouponEntities.stream().filter(a -> activityCouponConfigIds.contains(a.getCouponConfigId())).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(collect)){
            return null;
        }
        List<CMemberCanUseCouponListVO> collect1 = collect.stream().map(a -> {
            CMemberCanUseCouponListVO re = new CMemberCanUseCouponListVO();
            re.setCouponId(a.getId());
            MemberCouponConfigEntity couponConfig = memberCouponConfigService.getById(a.getCouponConfigId());
            re.setCouponName(couponConfig.getName());
            re.setCouponAmt(couponConfig.getRuleSubtract());
            return re;
        }).collect(Collectors.toList());
        return collect1;
    }

    public SHttpResponse<CMemberRechargeActivityVO> getRechargeActivity(Long orderAmt) {
        CMemberRechargeActivityVO cMemberRechargeActivityVO = new CMemberRechargeActivityVO();
        Integer currentUserId = SecurityUtil.getCurrentUserId();
        if (currentUserId==null){
            return SHttpResponse.fail(50001,"商户会员不存在");
        }
        MemberMerchantEntity currentMember2 = memberMerchantService.getById(currentUserId);
        MemberMerchantTmpEntity curretMemberTmp = memberMerchantTmpService.getById(currentUserId);
        String merchantCode = "";
        if (currentMember2 == null && curretMemberTmp == null){
            return SHttpResponse.fail(50001,"商户会员不存在");
        }
        if (curretMemberTmp!=null){
            merchantCode = curretMemberTmp.getMerchantCode();
        }
        if (currentMember2 !=null){
            merchantCode = currentMember2.getMerchantCode();
        }

        MemberCardConfigEntity memberCardConfigEntity = memberCardConfigService.getbyMerchantCode(merchantCode);
        if (memberCardConfigEntity == null){
            return SHttpResponse.ok(null);
        }
        List<MemberCardConfigDetailEntity> memberCardConfigDetailEntities = memberCardConfigDetailService.getbyConfigId(memberCardConfigEntity.getId());
        if (CollectionUtil.isEmpty(memberCardConfigDetailEntities) || memberCardConfigDetailEntities.size()!=3){
            return SHttpResponse.ok(null);
        }
        MemberCardConfigDetailEntity numberThree = getNumberThree(memberCardConfigDetailEntities, orderAmt);
        BeanUtils.copyProperties(numberThree,cMemberRechargeActivityVO);
        cMemberRechargeActivityVO.setRechargeAmt(numberThree.getDefaultAmt());
        cMemberRechargeActivityVO.setCardConfigDetailId(numberThree.getId());
        return SHttpResponse.ok(cMemberRechargeActivityVO);
    }
    public static MemberCardConfigDetailEntity getNumberThree(List<MemberCardConfigDetailEntity> intarray,Long number){
        long index = Math.abs(number-intarray.get(0).getDefaultAmt());
        MemberCardConfigDetailEntity result = intarray.get(0);
        for (MemberCardConfigDetailEntity i : intarray) {
            long abs = Math.abs(number-i.getDefaultAmt());
            if(abs <= index){
                index = abs;
                result = i;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        List<MemberCardConfigDetailEntity> intarray = new ArrayList<>();
        MemberCardConfigDetailEntity memberCardConfigDetailEntity1 = new MemberCardConfigDetailEntity();
        memberCardConfigDetailEntity1.setDefaultAmt(100L);
        memberCardConfigDetailEntity1.setId(1);
        intarray.add(memberCardConfigDetailEntity1);
        MemberCardConfigDetailEntity memberCardConfigDetailEntity2 = new MemberCardConfigDetailEntity();
        memberCardConfigDetailEntity2.setDefaultAmt(200L);
        memberCardConfigDetailEntity2.setId(2);
        intarray.add(memberCardConfigDetailEntity2);
        MemberCardConfigDetailEntity memberCardConfigDetailEntity3 = new MemberCardConfigDetailEntity();
        memberCardConfigDetailEntity3.setDefaultAmt(300L);
        memberCardConfigDetailEntity3.setId(3);
        intarray.add(memberCardConfigDetailEntity3);
        MemberCardConfigDetailEntity numberThree = getNumberThree(intarray, 300L);
        System.out.println(numberThree.getId());
    }
}
